from bs4 import BeautifulSoup
import re
import json
from .base import Handler
from event_engine.event_type import *
from event_engine.event import Event
from event_engine.engine import EventEngine
from models.task import *
from models.house import House, HOUSE_TYPE_SECONDARY

community_re = re.compile(r'qu\/(\d+)')


class SecondaryListHandler(Handler):
    """
    二手房列表
    """

    def process(self, event: Event, engine: EventEngine) -> None:
        html: str = event.data["html"]
        task: Task = event.data["task"]
        try:
            soup = BeautifulSoup(html, 'html.parser')
            self.parse_page(soup, task, engine)
            self.parse_house(soup, engine)
            task.complete()
        except Exception as e:
            print(e)

    def parse_page(self, soup: any, task: Task, engine: EventEngine):
        """
        解析列表页分页
        :param soup: BeautifulSoup对象
        :param task: 任务
        :param engine: 事件引擎实例
        :return:
        """
        is_first_page = False if re.search(r"\/pg\d+\/", task.url) else True
        if is_first_page:
            page = soup.find("div", "house-lst-page-box")
            if not page:
                return
            page_data = page.attrs["page-data"]
            total_page = json.loads(page_data)["totalPage"]
            for i in range(int(total_page)):
                if i > 0:
                    url: str = "%spg%s/" % (task.url, i + 1)
                    engine.put(Event(EVENT_SAVE_TASK, {
                        "type": TYPE_SECONDARY_LIST,
                        "url": url,
                        "referer": task.url,
                    }))

    def parse_house(self, soup: any, engine: EventEngine):
        """
        解析房屋信息
        :param soup: BeautifulSoup对象
        :param engine: 事件引擎实例
        :return:
        """
        ul = soup.find("ul", attrs={"class": "sellListContent"})
        if not ul:
            return
        div = soup.find("div", "crumbs")
        city = div.findChild("a").text.strip()[:-3]
        div = soup.find("div", attrs={"class": "position"})
        div = div.find("div", attrs={"data-role": "ershoufang"})
        district = div.find("a", "selected").text.strip()
        div = div.findChild("div")
        div = div.find_next_sibling("div")
        circle = div.find("a", "selected").text.strip()
        li_list = ul.findChildren("li", attrs={"data-lj_action_housedel_id": True})
        for li in li_list:
            position_info = li.find("div", "positionInfo")
            name_a = position_info.findChild("a")
            name = name_a.text.strip()
            ret = community_re.search(name_a.attrs['href'])
            if ret:
                community_code = ret.group(1)
            else:
                community_code = ""
            house_code = li.attrs["data-lj_action_housedel_id"]
            total_price = list(li.find("div", "totalPrice").children)
            price = float(total_price[0].text) * 10000 if total_price[1] == "万" else float(total_price[0].text)
            info = li.find("div", "houseInfo").text
            ret = re.search(r'(\d*)室(\d*)厅.*?([\d\.]*)平米', info)
            if ret:
                bedroom = ret.group(1)
                sitting_room = ret.group(2)
                area = ret.group(3)
            else:
                bedroom = 0
                sitting_room = 0
                area = 0

            engine.put(Event(EVENT_SAVE_HOUSE, {
                "type": HOUSE_TYPE_SECONDARY,
                "community_code": community_code,
                "house_code": house_code,
                "name": name,
                "city": city,
                "district": district,
                "circle": circle,
                "price": price,
                "area": area,
                "bedroom": bedroom,
                "sitting_room": sitting_room,
            }))
